package com.sunfeng.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sunfeng.common.utils.R;
import com.sunfeng.gulimall.product.entity.SkuImagesEntity;
import com.sunfeng.gulimall.product.entity.SpuInfoDescEntity;
import com.sunfeng.gulimall.product.feign.SeckillFeignService;
import com.sunfeng.gulimall.product.service.*;
import com.sunfeng.gulimall.product.vo.SeckillSkuVo;
import com.sunfeng.gulimall.product.vo.SkuItemSaleAttrVo;
import com.sunfeng.gulimall.product.vo.SkuItemVo;
import com.sunfeng.gulimall.product.vo.SpuItemAttrGroupVo;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunfeng.common.utils.PageUtils;
import com.sunfeng.common.utils.Query;

import com.sunfeng.gulimall.product.dao.SkuInfoDao;
import com.sunfeng.gulimall.product.entity.SkuInfoEntity;

import javax.annotation.Resource;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    // 图片信息
    @Autowired
    private SkuImagesService skuImagesService;

    //skuSaleAttrValueService
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        // 不等于零查询全部
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key) && !"0".equalsIgnoreCase(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price",min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(BigDecimal.ZERO) > 0) {
                    queryWrapper.le("price",max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // key:
        // catelogId: 225
        // brandId: 9
        // min: 0
        // max: 0

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     *  根据spuId 查询sku 信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {

        return   this.baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

    }

    /**
     * 查询商品详情
     * @param skuId
     * @return
     */
    @SneakyThrows
    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1、sku基本信息的获取  pms_sku_info   sku名称 默认图片   标题  副标题  价格
        CompletableFuture<SkuInfoEntity> skuInfoEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {

            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        },executor);

        //2、sku的图片信息  pms_sku_images
        CompletableFuture<Void> imagesEntitiesCompletableFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        },executor);



        //3、获取spu的销售属性组合
        CompletableFuture<Void> saleAttrVosCompletableFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((skuInfoEntity) -> {
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(skuInfoEntity.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        },executor);



        //4、获取spu的介绍
        CompletableFuture<Void> spuInfoDescEntityCompletableFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((skuInfoEntity) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(skuInfoEntity.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);




        //5、获取spu的规格参数信息
        CompletableFuture<Void> groupAttrsCompletableFuture = skuInfoEntityCompletableFuture.thenAcceptAsync(skuInfoEntity -> {
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());

            skuItemVo.setGroupAttrs(groupAttrs);

        }, executor);


        //6、秒杀商品的优惠信息
        CompletableFuture<Void> seckillSkuVoCompletableFuture = CompletableFuture.runAsync(() -> {
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfo.getCode() == 0) {
                //查询成功
                SeckillSkuVo seckillInfoData = skuSeckillInfo.getData("data", new TypeReference<SeckillSkuVo>() {
                });
                skuItemVo.setSeckillSkuVo(seckillInfoData);

                if (seckillInfoData != null) {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime > seckillInfoData.getEndTime()) {
                        skuItemVo.setSeckillSkuVo(null);
                    }
                }
            }
        });

      CompletableFuture.allOf(skuInfoEntityCompletableFuture, imagesEntitiesCompletableFuture, saleAttrVosCompletableFuture
                , spuInfoDescEntityCompletableFuture, groupAttrsCompletableFuture, seckillSkuVoCompletableFuture).get();;



        return skuItemVo;
    }

}